<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>d3.js Ear Clipping Algorithm Example</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <script src="/public/earcut.min.js"></script>
    <style>
        html, body, svg {
            margin: 0;
            overflow: hidden;
            width: 100%;
            height: 100%;
        }

        path {
            fill: none;
            stroke: #000;
            stroke-width: 2;
        }

        polyline {
            fill: none;
            stroke: #000;
            stroke-width: 2;
        }
    </style>
</head>
<body>
<svg id="svgContainer"></svg>

<script>
  // 定义多边形的顶点
  let polygonPoints = [[50, 100], [200, 50], [400, 150], [300, 300], [100, 300]];

  // 创建 SVG 容器
  let svgContainer = d3.select("#svgContainer");

  // 创建多边形路径
  let polygonPath = svgContainer.append("path")
    .attr("d", "M" + polygonPoints.join("L") + "Z"); // 创建闭合路径


  // let polygonPath = svgContainer
  //   .append("polyline")
  //   .attr("points", polygonPoints.map(x=>x.join(',')).join(' ')); // 创建闭合路径

  // 调用耳切法函数进行三角剖分
  let triangles2 = earcut(polygonPoints.reduce((a, b) => a.concat(b), []));
  // 绘制三角形
  // svgContainer.selectAll("polygon")
  //   .data(triangles)
  //   .enter().append("polygon")
  //   .attr("points", function (d) {
  //     return d.join(" ");
  //   })
  //   .style('fill', 'rgba(0,0,0,0.1)')

  console.log(triangles2)
  let arr = []
  for (let i = 0; i < triangles2.length; i += 3) {
    console.log(i)
    arr.push([polygonPoints[triangles2[i]], polygonPoints[triangles2[i + 1]], polygonPoints[triangles2[i + 2]]])
  }
  svgContainer
    .selectAll("path")
    .data(arr)
    .enter()
    .append("path")
    .attr("d", d => {
      debugger
      return "M" + d.join("L") + "Z"
    }); // 创建闭合路径

</script>
</body>
</html>
